import { _decorator, AudioClip, Component, director, log, tween, UITransform, v2, v3 } from 'cc';
const { ccclass, property, executionOrder } = _decorator;

import GameStorage from "../Data/GameStorage";
import { GameData } from "../Data/GameData";
import GamePanel from "../UI/GamePanel";
import SS_MapManager from "./SS_MapManager";
import { GameState, MainState } from "../Data/GameEnum";
import FailPanel from "../UI/FailPanel";
import WinPanel from "../UI/WinPanel";
import SS_GameEventManager from "./SS_GameEventManager";
import CardFunctions from "../Common/CardFunctions";
import SS_TimerManager from "./SS_TimerManager";
import Board from "../Game/Board";
import { ProductData } from "../Config/ProductData";
import SS_NodeManager from "./SS_NodeManager";
import Grid from "../Game/Grid";
import Card from "../Game/Card";
import { Consts } from "../Data/Consts";
import { bdlMgr } from "./SS_BundleManager";
import TAComponent from "../sdk/TAComponent";
import SS_UIManager from "./SS_UIManager";
import { MotionTrail } from '../utils/MotionTrail';
import { SS_AudioManager } from './SS_AudioManager';
import { SS_Settings } from '../Data/SS_Settings';
import CommonFunction from '../utils/CommonFunction';

// // 慢一点执行
@ccclass('SS_GameManager')
@executionOrder(100)
export default class SS_GameManager extends Component {
    static Instance: SS_GameManager;
    gameState: GameState;
    isCanOperate = true;

    onLoad() {
        SS_GameManager.Instance = this;

        this.Init();
    }

    async Init() {
        SS_GameEventManager.AddListener();

        SS_UIManager.Instance.ResetUINode();

        SS_GameManager.Instance.StartGame();
    }

    async StartGame() {
        await SS_TimerManager.AwaitTime(0.01);

        GameData.InitData();

        SS_MapManager.Instance.initMap();
        GamePanel.Instance.ShowOn();

        // bdlMgr.getRes<AudioClip>(Consts.BundleName.AUDIO, `bgm/关卡内BGM`, AudioClip).then(async (audio) => {
        //     SS_AudioManager.Instance.play(audio, SS_Settings.curMusicV);
        // });

        let data = CardFunctions.获取关卡属性(GameData.Get_CurrentLevel())
        let isWujin = data.isWujin;
        let level = data.level;
        let model = isWujin ? "wujin" : "normal";
        TAComponent.SendEvent(Consts.埋点事件.level_start, { level: level + 1, model: model });
    }

    async ReStartGame() {
        director.loadScene("GameScene");
    }
    async ExitGame() {
        director.loadScene("MainScene");
    }
    async NextStage() {
        director.loadScene("MainScene");
    }

    //    // 吃海底捞
    async Main() {
        //        // 1-等待叫号
        //        // 2-排到号，上桌
        //        // 3-检测是否上面等候区有凳子空了
        //        // 4-没空就结束循环
        //        // 5-空了就撤凳子
        //        // 6-撤完凳子在检测新的客人是否有新的匹配
        //        // 7-没有匹配就结束循环
        //        // 8-有匹配就循环第2部-上桌

        if (GameData.mainState === MainState.飞) {
            GameData.装填list = CardFunctions.获取上桌数据()
            if (GameData.装填list.length > 0) {
                await SS_GameManager.Instance.飞();

                GameData.装填list = [];
                GameData.mainState = MainState.撤凳子;
                SS_GameManager.Instance.Main();
            }
            else {
                SS_GameManager.Instance.结束还是继续();
            }
        }
        else if (GameData.mainState === MainState.撤凳子) {
            // console.log("撤凳子");

            GameData.撤凳子list = CardFunctions.获取撤凳子数据()
            // console.log(" GameData.撤凳子list", GameData.撤凳子list);

            if (GameData.撤凳子list.length > 0) {
                await SS_GameManager.Instance.撤凳子();

                CardFunctions.SetAllBoardCover();

                GameData.撤凳子list = [];
                GameData.mainState = MainState.飞;
                SS_GameManager.Instance.Main();
            }
            else {
                SS_GameManager.Instance.结束还是继续();
            }
        }
    }

    结束还是继续() {
        if (GameData.是否等待消除) {
            GameData.是否等待消除 = false;
            GameData.mainState = MainState.飞;
            SS_GameManager.Instance.Main();
        }
        else {
            GameData.是否正在消除 = false;
            SS_GameManager.Instance.回合结束();
        }
    }

    解锁() {
        let item = ProductData.find(e => e.unlock === GameData.CurrentLevel + 1);
        if (item) {
            if (!GameStorage.data.unlock_list_role.find(x => x === item.id)) {
                GameStorage.data.unlock_list_role.push(item.id);
                GameStorage.saveData();

                GameData.currentUnlockId = item.id;
            }
        }
    }

    async 回合结束() {
        // console.log("回合结束");

        await SS_TimerManager.AwaitTime(0.1);

        if (SS_GameManager.Instance.是否成功()) {
            SS_GameManager.Instance.成功();

            return;
        }

        if (SS_GameManager.Instance.是否失败()) {
            console.log("失败-----------------");

            SS_GameManager.Instance.失败();

            return;
        }

        GameData.mainState = MainState.空闲;
    }
    async 复活() {
        // bdlMgr.getRes<AudioClip>(Consts.BundleName.AUDIO, `bgm/关卡内BGM`, AudioClip).then(async (audio) => {
        //     SS_AudioManager.Instance.play(audio, SS_Settings.curMusicV);
        // });

        CardFunctions.禁止操作(false);

        GameData.本关剩余复活次数--;

        let array_id_block = CardFunctions.GetAll空格子();
        // console.log("array", array_id_block);

        // GameData.arrBoard.sort((a, b) => b.layer - a.layer);
        let copy_arrBoard = GameData.arrBoard.concat();
        copy_arrBoard.sort((a, b) => b.layer - a.layer);

        let array_id_board = [];
        let array_card = [];

        for (let index = 0; index < copy_arrBoard.length; index++) {
            const board: Board = copy_arrBoard[index];

            for (let index2 = 0; index2 < board.cardList.length; index2++) {
                const card: Card = board.cardList[index2];
                if (card.id > 0) {
                    array_id_board.push(card.id);
                    array_card.push(card);
                }
            }
        }

        // console.log("array_id_board", array_id_board);

        let array_1 = [];

        for (let index = 0; index < array_id_block.length; index++) {
            const id = array_id_block[index];

            let index_1 = array_id_board.indexOf(id);
            if (index_1 > -1) {
                array_1.push(id);
                array_id_board.splice(index_1, 1);
            }
        }

        // console.log("array_1", array_1);
        // console.log("array_id_board", array_id_board);

        array_id_board = array_1.concat(array_id_board);

        // console.log("array_id_board", array_id_board);

        for (let index = 0; index < array_card.length; index++) {
            const card: Card = array_card[index];
            const id: number = array_id_board[index];
            card.id = id
            card.Refresh2();
        }

        SS_GameEventManager.拖拽完成();
    }

    async 成功() {
        // console.log("成功~~~~");

        CardFunctions.禁止操作(true);

        //如果有解锁就解锁，包含判断逻辑
        SS_GameManager.Instance.解锁();

        // console.log("GameStorage.data.CurrentLevel", GameStorage.data.CurrentLevel);

        {
            let data = CardFunctions.获取关卡属性(GameData.Get_CurrentLevel())
            let isWujin = data.isWujin;
            let level = data.level;
            let model = isWujin ? "wujin" : "normal";
            TAComponent.SendEvent(Consts.埋点事件.level_end, { level: level + 1, model: model });
        }

        GameStorage.data.CurrentLevel++;
        GameStorage.saveData();
        GameData.CurrentLevel = GameStorage.data.CurrentLevel;

        // console.log("GameStorage.data.CurrentLevel", GameStorage.data.CurrentLevel);
        // console.log("GameData.CurrentLevel", GameData.CurrentLevel);


        let isWujin = CardFunctions.是否是无尽模式(GameData.Get_CurrentLevel())
        // console.log("是否是无尽模式", isWujin);
        if (isWujin) {
            CardFunctions.生成无尽模式数据();
        }

        SS_AudioManager.Instance.stop();
        // bdlMgr.getRes<AudioClip>(Consts.BundleName.AUDIO, `sound/过关胜利音效`, AudioClip).then(async (audio) => {
        //     SS_AudioManager.Instance.playOneShot(audio, SS_Settings.curMusicV);
        // });

        SS_UIManager.Instance.CreatePanel(`UI/WinPanel`, WinPanel);
    }

    async 失败() {
        CardFunctions.禁止操作(true);

        for (let x = 0; x < GameData.col; x++) {
            for (let y = 0; y < GameData.row; y++) {
                const grid: Grid = CardFunctions.GetGrid(x, y);
                let 当前格子是否是空地 = CardFunctions.当前格子是否是空地(grid.x, grid.y);
                if (当前格子是否是空地) {
                    grid.Flash();
                }
            }
        }

        await SS_TimerManager.AwaitTime(1.4);


        SS_AudioManager.Instance.stop();
        bdlMgr.getRes<AudioClip>(Consts.BundleName.AUDIO, `sound/游戏失败`, AudioClip).then(async (audio) => {
            SS_AudioManager.Instance.playOneShot(audio, SS_Settings.curMusicV);
        });

        SS_UIManager.Instance.CreatePanel(`UI/FailPanel`, FailPanel);
    }

    上一关() {
        GameData.CurrentLevel--;
        director.loadScene("GameScene");
    }
    下一关() {
        GameData.CurrentLevel++;
        director.loadScene("GameScene");
    }

    是否成功() {
        if (GameData.arrBoard.length === 0) {
            return true;
        }
        else {
            return false;
        }
    }

    是否失败() {
        return !CardFunctions.是否可以放得下();
    }

    后面是否有新凳子() {
        // for (let index_board = 0; index_board < GameData.arrBoard.length; index_board++) {
        // const board: Board = GameData.arrBoard[index_board];
        //            // console.log("board", board);
        //            // console.log("board.cardList", board.cardList);

        // const isBoardCover = CardFunctions.IsBoardCover(board);
        // if (isBoardCover !== board.isCover) {
        // return true;
        // }
        // }

        // return false;
    }

    async 后面凳子亮出来() {
        CardFunctions.SetAllBoardCover();

        GameData.mainState = MainState.开始;
        SS_GameManager.Instance.Main();
    }

    async 撤凳子() {
        let count = 0;
        for (let index = 0; index < GameData.撤凳子list.length; index++) {
            const board: Board = GameData.撤凳子list[index];
            await board.Dead();
            count++;
        }

        if (count >= GameData.撤凳子list.length) {
            await SS_TimerManager.AwaitTime(0.01);
        }
    }

    //    /** 上桌 */
    async 飞() {
        let 装填list = GameData.装填list;

        // console.log("GameData.装填list", GameData.装填list);


        for (let index = 0; index < 装填list.length; index++) {
            const item = 装填list[index];

            let 拖尾: MotionTrail = item.card.node.getComponent(MotionTrail);
            // 拖尾.length = 14;
            // 拖尾.headWidth = 50;
            拖尾.headOpacity = 255;


            // let p_w = item.card.node.convertToWorldSpaceAR(v3(0, 0, 0));
            let p_w = item.card.node.worldPosition;
            item.card.node.parent = SS_NodeManager.Instance.Root_fly;
            // let p_n = item.card.node.parent.convertToNodeSpaceAR(p_w);
            let p_n = item.card.node.parent.getComponent(UITransform).convertToNodeSpaceAR(p_w);


            item.card.node.position = p_n;


            // let p1 = item.block.node.convertToWorldSpaceAR(v3(0, 0, 0));
            // let p2 = item.card.node.parent.convertToNodeSpaceAR(p1);
            let p1 = item.block.node.worldPosition;
            let p2 = item.card.node.parent.getComponent(UITransform).convertToNodeSpaceAR(p1);



            // tween(item.card.node)
            //     .by(1, { position: v3(0, item.card.node.position.y + 10, 0) })

            // .bezierTo(0.3, item.card.node.position, v2(400, 600), p2)
            // .to(0.3, { position: p2 })
            // CommonFunction.bezierTo(item.card.node, 0.3, item.card.node.position, v2(400, 600), p2, null)
            // CommonFunction.bezierTo(item.card.node, 0.5, item.card.node.position, v2(400, 600), p2, null)

            let mid = v3(item.card.node.position.x + 200, item.card.node.position.y + 200);
            CommonFunction.bezierTo(item.card.node, 0.3, item.card.node.position, mid, p2, null)
                // .start()

                .call(async () => {
                    item.card.node.parent = item.block.node;
                    item.card.node.position = v3(0, 0, 0);
                    item.card.node.setScale(1, 1, 1);

                    item.block.is装填完成 = true;

                    tween(item.blockGroup.node)
                        .by(0.05, { scale: v3(0.1, 0.1, 0.1) })
                        .by(0.05, { scale: v3(-0.1, -0.1, -0.1) })
                        .start();

                    bdlMgr.getRes<AudioClip>(Consts.BundleName.AUDIO, `sound/提起俄罗斯方块`, AudioClip).then(async (audio) => {
                        SS_AudioManager.Instance.playOneShot(audio, SS_Settings.curMusicV);
                    });


                    if (item.blockGroup.是否该结账了()) {
                        item.blockGroup.结账();
                    }
                })
                .start();
            await SS_TimerManager.AwaitTime(0.2);
        }

        await SS_TimerManager.AwaitTime(0.01);
    }
}

/** 调试 */
window["SS_GameManager"] = SS_GameManager;